package com.sunriz.ctrl.views.common;

import com.fazecast.jSerialComm.SerialPort;
import com.ghgande.j2mod.modbus.facade.ModbusSerialMaster;
import com.sunriz.ctrl.MainApplication;
import com.sunriz.ctrl.server.utils.scada.Timer;
import com.sunriz.ctrl.server.utils.serial.ModbusRtuManger;
import com.sunriz.ctrl.server.utils.serial.ModbusServer;
import com.sunriz.ctrl.views.ScadaController;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
/**
 * ClassName: NavBar
 * Package: com.sunriz.ctrl.views
 * Description:
 *
 * @Author BuTang
 * @Create 2025/1/16 10:10
 * @Version 1.0
 */
public class NavBar {

    private static Stage settingsStage = null;
    /**
     * 创建并返回一个配置好的导航栏
     * @param stage 主界面
     * @return 创建并返回一个配置好的导航栏
     */
    public static HBox createScadaNavBar(Stage stage) {
        // 创建导航栏
        HBox navBar = new HBox();
        navBar.setStyle("-fx-background-color: #34495e; " + // 深灰色背景
                "-fx-padding: 10px; " +
                "-fx-alignment: center-left; " +
                "-fx-spacing: 15;"); // 设置间距

        // 设置按钮样式
        String buttonStyle = "-fx-background-color: #ecf0f1; " + // 浅灰色背景
                "-fx-background-insets: 0, 1, 2; " +
                "-fx-background-radius: 2px; " +
                "-fx-text-fill: #2c3e50; " + // 深灰色文字
                "-fx-border-color: #7f8c8d; " + // 边框颜色
                "-fx-border-insets: 1; " +
                "-fx-border-radius: 2px; " +
                "-fx-font-weight: bold; " +
                "";

        // 设置按钮动作
        Button btnHome = new Button("首页");
        btnHome.setOnAction(e -> MainApplication.show(stage));
        btnHome.setStyle(buttonStyle);

        // 设置按钮并跳出新界面
        Button btnSettings = new Button("连接");
        btnSettings.setStyle(buttonStyle);
        btnSettings.setOnAction(e -> {
            createConnectShow();
        });

        Button btnHelp = new Button("帮助");
        btnHelp.setStyle(buttonStyle);

        // 将按钮添加到导航栏
        navBar.getChildren().addAll(btnHome, btnSettings, btnHelp);
        HBox.setMargin(btnHome, new Insets(0, 0, 0, 0));
        HBox.setMargin(btnSettings, new Insets(0, 0, 0, 0));
        HBox.setMargin(btnHelp, new Insets(0, 10, 0, 0));
        return navBar;
    }

    /**
     * 创建连接界面
     */
    private static void createConnectShow(){
        if (settingsStage != null && settingsStage.isShowing()) {
            settingsStage.toFront();
            return;
        }
        // 创建新界面（Stage）
        settingsStage = new Stage();
        settingsStage.setTitle("配置连接");

        // 创建VBox布局
        VBox vbox = new VBox();
        vbox.setSpacing(15); // 设置控件间距
        vbox.setPadding(new Insets(20));

        // 创建ComboBox：串口
        ComboBox<String> comboBox = new ComboBox<>();
        SerialPort[] commPorts = SerialPort.getCommPorts();
        for (SerialPort port : commPorts) {
            String name = port.getSystemPortName();
            comboBox.getItems().add(name);
        }
        // 如果没有可用串口，可以设置一个默认选项
        if (!comboBox.getItems().isEmpty()) {
            comboBox.setValue(comboBox.getItems().get(0));  // 默认选择第一个串口
        }

        HBox comboBoxBox = new HBox(10, new Label("Serial Port: "), comboBox);
        comboBoxBox.setAlignment(Pos.CENTER_LEFT);

        // 创建ComboBox：波特率
        ComboBox<String> baudRateComboBox = new ComboBox<>();
        baudRateComboBox.getItems().addAll("9600", "115200", "256000");
        baudRateComboBox.setValue("115200");
        HBox baudRateBox = new HBox(10, new Label("Baud Rate: "), baudRateComboBox);
        baudRateBox.setAlignment(Pos.CENTER_LEFT);

        // 创建ComboBox：数据位
        ComboBox<String> dataBitsComboBox = new ComboBox<>();
        dataBitsComboBox.getItems().addAll("7", "8");
        dataBitsComboBox.setValue("8");
        HBox dataBitsBox = new HBox(10, new Label("Data   Bits: "), dataBitsComboBox);
        dataBitsBox.setAlignment(Pos.CENTER_LEFT);

        // 创建ComboBox：奇偶校验
        ComboBox<String> parityComboBox = new ComboBox<>();
        parityComboBox.getItems().addAll("None", "Odd", "Even");
        parityComboBox.setValue("None");
        HBox parityBox = new HBox(10, new Label("Parity: "), parityComboBox);
        parityBox.setAlignment(Pos.CENTER_LEFT);

        // 创建ComboBox：停止位
        ComboBox<String> stopBitsComboBox = new ComboBox<>();
        stopBitsComboBox.getItems().addAll("1", "1.5", "2");
        stopBitsComboBox.setValue("1");
        HBox stopBitsBox = new HBox(10, new Label("Stop   Bits: "), stopBitsComboBox);
        stopBitsBox.setAlignment(Pos.CENTER_LEFT);

        // 创建文本框：响应超时
        TextField timeoutField = new TextField("200");
        timeoutField.setPromptText("Response Timeout");
        HBox timeoutBox = new HBox(10, new Label("Response  Timeout: "), timeoutField);
        timeoutBox.setAlignment(Pos.CENTER_LEFT);

        // 创建文本框：延迟设置
        TextField retriesField = new TextField("3");
        retriesField.setPromptText("清楚如重试次数");
        HBox retriesBox = new HBox(10, new Label("retry count: "), retriesField);
        retriesBox.setAlignment(Pos.CENTER_LEFT);

        // 创建按钮布局
        HBox buttonBox = new HBox(20);
        Button connectButton = new Button("Connect");
        connectButton.setOnAction(event ->
                {
                    ModbusRtuManger instance = ModbusRtuManger.getInstance();
                    ModbusSerialMaster rtu = instance.create(
                            comboBox.getValue(),
                            Integer.valueOf(baudRateComboBox.getValue()),
                            Integer.valueOf(dataBitsComboBox.getValue()),
                            Integer.valueOf(stopBitsComboBox.getValue()),
                            parityComboBox.getValue(),
                            "RTU",
                            Integer.valueOf(timeoutField.getText()),
                            Integer.valueOf(retriesField.getText())
                    );
//                    ModbusServer.readRegister();
                    Thread thread = new Thread(() -> ModbusServer.readRegister());
                    thread.start();
                    Timer.startUpdatingTable();
                    settingsStage.close();
                }
        );
        Button disConnect = new Button("Disconnect");
        disConnect.setOnAction(event ->
                {
                    ModbusServer.stopRead();
                    ModbusRtuManger.getInstance().disConnect();
                    settingsStage.close();
                    Timer.stopUpdatingTable();
                }
        );
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        buttonBox.getChildren().addAll(connectButton, disConnect);

        // 将所有控件添加到VBox
        vbox.getChildren().addAll(comboBoxBox, baudRateBox, dataBitsBox, parityBox, stopBitsBox, timeoutBox, retriesBox, buttonBox);

        // 设置新窗口的场景和大小
        Scene scene = new Scene(vbox, 400, 350);
        settingsStage.setScene(scene);
        settingsStage.show();

        // 确保连接界面始终在前面
        settingsStage.toFront();

        // 请求焦点
        settingsStage.requestFocus();
    }

}
